//
//  DownloadManager.m
//  ImGuider
//
//  Created by llt on 2017/8/4.
//  Copyright © 2017年 AudioCtrip. All rights reserved.
//

#import "DownloadManager.h"
#import "DownloadListDAO.h"

#import "FileManager.h"

@interface DownloadManager ()

@property (nonatomic, strong) MCDownloader *downloader;
@property (nonatomic, strong) NSOperationQueue *oprationQueue;

@end

@implementation DownloadManager

+ (instancetype)sharedManager {
    
    static id instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        instance = [[self alloc] init];
    });
    
    return instance;
}

- (instancetype)init {
    
    self = [super init];
    if (self) {
        
        _downloader = [MCDownloader sharedDownloader];
        _downloader.maxConcurrentDownloads = 3;
        _oprationQueue = [[NSOperationQueue alloc] init];
        _oprationQueue.maxConcurrentOperationCount = 1;//指定池子的并发数
    }
    return self;
}

- (MCDownloadReceipt *)downloadReceiptForURLString:(NSString *)URLString {
    
    MCDownloadReceipt *receipt = [self.downloader downloadReceiptForURLString:URLString];
    
    return receipt;
}

- (long long )fileSizeForURLString:(NSString *)URLString {
    
    MCDownloadReceipt *receipt = [self.downloader downloadReceiptForURLString:URLString];
    
    if (receipt.state == MCDownloadStateCompleted) {

        return [FileManager fileLengthForPath:receipt.filePath];
    }
    return 0;
}

- (void)downloadStatusForModel:(LineModel *)model block:(void(^)(MCDownloadState state,NSInteger completeCount, NSString *unionid))block {
    
    @weakify(self);
    
    
    [self.oprationQueue addOperationWithBlock:^{
        
        @strongify(self);
        __block LineModel *dbmodel = nil;
        [DownloadListDAO getLineModelWithUnionid:model.unionid Block:^(LineModel *lineModel) {
            
            dbmodel = lineModel;
            
        }];
        
        if (!dbmodel) {
            
            dispatch_main_async_safe( ^{
                
                block(MCDownloadStateNone,0,model.unionid);
            });
            
            
            return;
        }
        
        if (![dbmodel.lineid isEqualToString:model.lineid]) {
            model.isUpdate = YES;
        }
        
        
        model.isSuspend = dbmodel.isSuspend;
        
        if (model.isSuspend) {
            
            dispatch_main_async_safe( ^{
                block(MCDownloadStateSuspened,0,model.unionid);
            });
            
            return;
        }
        
        
        NSInteger completeCount = 0;
        NSInteger failedCount = 0;
        
        for (ScenicPoint *point in model.records) {
            
            MCDownloadReceipt *receipt = [self.downloader downloadReceiptForURLString:point.playpath];
            
            if (receipt.state == MCDownloadStateCompleted) {
                completeCount ++;
            } else if (receipt.state == MCDownloadStateFailed) {
                failedCount ++;
            }
        }
        
        MCDownloadState state = MCDownloadStateDownloading;
        
        if ((completeCount + failedCount) == model.records.count) {
            
            if (failedCount > 0) {
                state = MCDownloadStateFailed;
            } else {
                state = MCDownloadStateCompleted;
            }
        }
        
        dispatch_main_async_safe( ^{
            block (state,completeCount,model.unionid);
        });
        
    }];
}

/**
 增加下载
 
 @param lineModel lineModel对象
 
 */
- (void)addDownloadWithLineModel:(LineModel *)lineModel  {
    
    if (lineModel.unionid.length == 0) {
        return;
    }
    @weakify(self);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        @strongify(self);
        [DownloadListDAO insertLineModel:lineModel];
        
//        [self downloadPictures:lineModel];
        
        for (ScenicPoint *point in lineModel.records) {
            
            NSString *path = point.playpath;
            if (path.length == 0) {
                continue;
            }
            
            [self.downloader downloadDataWithURL:[NSURL URLWithString:path] progress:nil completed:nil];
        }
        [DownloadListDAO insertScenicArray:lineModel.records unionid:lineModel.unionid];
    });
}

- (void)addDownloadWithLineModel:(LineModel *)lineModel point:(ScenicPoint *)point {
    
    if (lineModel.unionid.length == 0) {
        return;
    }
    
    @weakify(self);

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        
        @strongify(self);
        [DownloadListDAO insertLineModel:lineModel];
        
        [self downloadPictures:lineModel];
        
        NSString *path = point.playpath;
        
        if (path.length == 0) {
            
            return;
        }
        [self.downloader downloadDataWithURL:[NSURL URLWithString:path] progress:nil completed:nil];
        [DownloadListDAO insertScenicArray:lineModel.records unionid:lineModel.unionid];
    });
}

- (void)downloadPictures:(LineModel *)model {
    
    for (ScenicPoint *point in model.records) {
        
        for (NSString *urlstr in point.pictureArray) {
            
            if (!urlstr) {
                continue;
            }
            
            UIImage *image = [FileManager getImageInDirectory:kPath_ImageSave url:urlstr];
            if (image) {
                continue;
            }
            NSURL *imageURL = [NSURL URLWithString:urlstr];
            
            [UIImageView downloadImageWithURL:imageURL progress:nil completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
                
                [FileManager saveImage:image InDirectory:kPath_ImageSave url:urlstr];
            }];
        }
    }
    
    for (NSString *mapStr in model.mapPicArray) {
        
        if (!mapStr) {
            continue;
        }
        
        NSURL *imageURL = [NSURL URLWithString:mapStr];
        
        [UIImageView downloadImageWithURL:imageURL progress:nil completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
            
            [FileManager saveImage:image InDirectory:kPath_ImageSave url:mapStr];
        }];
    }
}


/**
 停止下载，删除对象
 
 @param lineModel lineModel对象
 */
- (void)deleteDownloadWithLineModel:(LineModel *)lineModel {
    
    @weakify(self);
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        
        @strongify(self);
        for (ScenicPoint *point in lineModel.records) {
            
            MCDownloadReceipt *receipt = [self.downloader downloadReceiptForURLString:point.playpath];
            
            [self.downloader remove:receipt completed:nil];
            
            for (NSString *url in point.pictureArray) {
                
                if (!url) {
                    continue;
                }
                
                [FileManager deleteImageInDirectory:kPath_ImageSave url:url];
            }
        }
        
        for (NSString *mapStr in lineModel.mapPicArray) {
            
            if (!mapStr) {
                continue;
            }
            
            [FileManager deleteImageInDirectory:kPath_ImageSave url:mapStr];
        }
        
        [DownloadListDAO deleteLineModelUnionid:lineModel.unionid];
    });
}

/**
 停止下载，不删除对象
 
 @param lineModel lineModel对象
 */
- (void)pauseWithLineModel:(LineModel *)lineModel {
    
    @weakify(self);
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        
        @strongify(self);
        for (ScenicPoint *point in lineModel.records) {
            MCDownloadReceipt *receipt = [self.downloader downloadReceiptForURLString:point.playpath];
            
            if (receipt.state != MCDownloadStateCompleted) {
                
                [self.downloader cancel:receipt completed:nil];
            }
        }
        
        [DownloadListDAO pauseLineModelUnionid:lineModel.unionid];
    });
}

- (void)beginAllDownloading {
    
    @weakify(self);
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        @strongify(self);
        __block NSArray *sArray = nil;
        [DownloadListDAO getAllScenicPointBlock:^(NSArray<ScenicPoint *> *scenicArray) {
            
            sArray = scenicArray;
        }];
        
        for (ScenicPoint *point in sArray) {
            
            MCDownloadReceipt *receipt = [self.downloader downloadReceiptForURLString:point.playpath];
            
            if (receipt.state != MCDownloadStateCompleted && receipt.state != MCDownloadStateFailed && receipt.state != MCDownloadStateSuspened && receipt.url) {
                
                [self.downloader downloadDataWithURL:[NSURL URLWithString:receipt.url] progress:nil completed:nil];
            }
        }
    });
    
}

@end

